package com.example.bishop.musicplayer_1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

//import java.lang.Thread;
import java.io.IOException;
import java.util.ArrayList;

public class Button_Bottom extends AppCompatActivity implements View.OnClickListener {
    private TextView songTv_1, singerTv_1;
    private Button btn_last, btn_start, btn_next;
    private SeekBar seekBar;
    private LocalMusicBean musicBean;
 //   public Thread updateSeekBar;
    public int i = 1;
    private MusicAdapter adapter;
    int currentPausePositionInSong = 0;//播放歌曲的进度
    public MediaPlayer mediaPlayer;
    private ArrayList mDatas;
    private int position;
    DatabaseHelper databaseHelper;
    SQLiteDatabase database;
   // int totalDuration = mediaPlayer.getDuration();
    int currentPausePosition1 = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button__bottom);

        //数据库
        databaseHelper =new DatabaseHelper(this,"songs",null,1);
        database=databaseHelper.getWritableDatabase();

        //绑定控件
        btn_start = findViewById(R.id.btn_bottom1_start);
        btn_last = findViewById(R.id.btn_bottom1_last);
        btn_next = findViewById(R.id.btn_bottom1_next);
        songTv_1 = findViewById(R.id.tv_top_song);
        singerTv_1 = findViewById(R.id.tv_top_singer);
        seekBar = findViewById(R.id.seekBar);
        mediaPlayer = new MediaPlayer();

        Bundle extras = getIntent().getExtras();
        mDatas = (ArrayList) extras.getSerializable("mData_key");

        /* 旧版数据传递 用数据库代替
        position = extras.getInt("positionkey");//第几首
        currentPausePositionInSong = extras.getInt(MainActivity.CurrentPositionkey);//播放进度  有时候快几毫秒，有时候慢
        */
        //通过数据库查询数据
        searchDatabase();

        musicBean = (LocalMusicBean) mDatas.get(position);//读取列表中的第position首歌
        System.out.println(currentPausePositionInSong);
        mediaPlayer.reset();
        //设置新的播放路径
        try {
            mediaPlayer.setDataSource(musicBean.getPath());//设置播放路径
            System.out.println(musicBean.getPath());
            mediaPlayer.prepare();
            mediaPlayer.seekTo(currentPausePositionInSong);
            mediaPlayer.start();
            handler.post(updateThread);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //playMusic();
        //由于调用了新的mediaplay，需要写返回事件！返回播放位置，以及歌曲url；
        updateSingInfo(1);


//老板的传递歌手和歌名，弃用
        //  String singerr=extras.getString("singer");
        // String songr=extras.getString("song");
        //  songTv_1.setText(songr);
        // singerTv_1.setText(singerr);
        // songTv_1.setSelected(true);
        // singerTv_1.setSelected(true);


        //设置控件的点击事件
        btn_start.setOnClickListener(this);
        btn_next.setOnClickListener(this::onClick);
        btn_last.setOnClickListener(this::onClick);

        //playMusic();

/*
        //想用个线程刷新seekbar，但报错了
        updateSeekBar = new Thread(() -> {
           // super.run();
            while (currentPausePosition1 < totalDuration) {
                try {
                    Thread.sleep(500);
                    currentPausePosition1 = mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(currentPausePosition1);
                } catch (InterruptedException | IllegalStateException e) {
                    e.printStackTrace();
                }
            }
        });
        seekBar.setMax(mediaPlayer.getDuration());
        updateSeekBar.start();*/

        //seekBar手动更新
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser==true){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }
    //进度条更新
    Handler handler=new Handler();
    Runnable updateThread=new Runnable() {
        @Override
        public void run() {
            seekBar.setMax(mediaPlayer.getDuration());
            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            handler.postDelayed(updateThread,100);
        }
    };

    //更新歌曲信息
    private void updateSingInfo(int n) {
        switch (n) {
            case 1:
                songTv_1.setText(musicBean.getSong());
                singerTv_1.setText(musicBean.getSinger());
                break;
            case 2:
                if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    btn_start.setBackgroundResource(0);
                    btn_start.setBackgroundResource(R.drawable.play1);
                    handler.post(updateThread);
                    playMusic();
                } else {
                    btn_start.setBackgroundResource(0);
                    btn_start.setBackgroundResource(R.drawable.pause1);
                    handler.removeCallbacks(updateThread);
                    pauseMusic();
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_bottom1_start:
                /*if (mediaPlayer!=null&&!mediaPlayer.isPlaying()) {
                    btn_start.setBackgroundResource(0);
                    btn_start.setBackgroundResource(R.drawable.play1);i++;
                    playMusic();
                    break;
                }else
                {  btn_start.setBackgroundResource(0);
                    btn_start.setBackgroundResource(R.drawable.pause1);i++;
                    pauseMusic();*/
                updateSingInfo(2);
                break;
            case R.id.btn_bottom1_next:
                position++;
                setMediaPlay(position);
                playMusic();
                updateSingInfo(1);
                break;
            case R.id.btn_bottom1_last:
                position--;

                setMediaPlay(position);
                playMusic();
                updateSingInfo(1);
                break;
        }
    }


    private void playMusic() {//播放音乐的函数
        if (mediaPlayer != null && !mediaPlayer.
                isPlaying()) {
            if (currentPausePositionInSong == 0) {//从头开始播放
                try {
                    mediaPlayer.prepare();
                    mediaPlayer.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {//从暂停处继续播放
                mediaPlayer.seekTo(currentPausePositionInSong);
                mediaPlayer.start();
            }
//            playIv.setBackgroundResource(0);
//            playIv.setImageResource(R.drawable.play1);
        }
    }

    private void stopMusic() {//停止音乐
        if (mediaPlayer != null) {
            currentPausePositionInSong = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            //    playIv.setImageResource(R.drawable.pause1);
        }
    }

    private void pauseMusic() {//暂停音乐
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            currentPausePositionInSong = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            //  playIv.setImageResource(R.drawable.pause1);
        }
    }

    //设置播放地址
    private void setMediaPlay(int position) {
        musicBean = (LocalMusicBean) mDatas.get(position);
        stopMusic();
        mediaPlayer.reset();
        try {
            // mediaPlayer.prepare();
            mediaPlayer.setDataSource(musicBean.getPath());

            // currentPausePositionInSong=0;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //重写返回按钮，返回播放歌曲及进度
  /*  @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent=new Intent();
        intent.putExtra("positionkey",position);//返回歌曲位置
        intent.putExtra("currentPosition",currentPausePositionInSong);//返回歌曲播放位置
        System.out.println(intent);
        setResult(RESULT_OK,intent);
        pauseMusic();
        finish();
    }
*/
    //插入数据库
    public void insertDatabase(int p,int c){
        ContentValues values=new ContentValues();
        values.put("position",p);
        values.put("currition",c);
        database.insert("song_info",null,values);

    }
    //查询数据库，读到最后的位置
    public void searchDatabase(){
        Cursor cursor=database.query("song_info",new String[]{"position","currition"},null,null,null,null,null);
        if (cursor.moveToLast()){
            position=cursor.getInt(cursor.getColumnIndex("position"));
            currentPausePositionInSong=cursor.getInt(cursor.getColumnIndex("currition"));
            // System.out.println(a +" "+b);}
        }
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //Intent intent = new Intent();
        pauseMusic();
        //将当前歌曲信息写入数据库
        insertDatabase(position,mediaPlayer.getCurrentPosition());
        System.out.println(position+" hhh"+mediaPlayer.getCurrentPosition());
        //intent.putExtra("positionkey", position);//返回歌曲位置
        // intent.putExtra(MainActivity.CurrentPositionkey,currentPausePositionInSong);//返回歌曲播放位置
       // Button_Bottom.this.setResult(1008611, intent);
        finish();//为啥返回为空。。。。
    }


}
